
var ScanBar = require("./plugin/scan/scanbar.js");
let intervarID;
//1、beginTime    需要倒计时的时间，比如："01:11:12"，默认值为"00:00:00"
// 2、fn      倒计时归零0时的回调函数，如果为beginTime = "00:00:00"则立即调用
// 3、interval     倒计时的过程中，规定每隔几秒执行一次intervalFn，如果为0则永远不会执行，默认为1
// 4、intervalFn    每隔interval秒执行一次的函数。

function wxTimer(beginTime = "00:00", fn, interval = 1, intervalFn) {
    var getTime = new Date("2018/01/01 00:" + beginTime);
    //初始化定时器
    this.setData({
        wxTimer: beginTime
    });
    this.scanBar = new ScanBar();

    //开始倒计时
    var that = this;
    var count = 0;
    //倒计时定时器
    intervarID = setInterval(function () {
        var tmpTime = new Date(getTime.getTime() - 1000 * count++).toString().substr(19, 5);
        that.setData({
            wxTimer: tmpTime
        });
        if (that.data.doorStatus !== 1) {
            console.log(`# wxTimer_that.data.doorStatus(${that.data.doorStatus})`);
            stop();

            that.scanBar.stopScan(true);
            return;
        }
        console.log(`# wxTimer_that.data.wxTimer(${that.data.wxTimer}),intervarID${intervarID}`);

        that.scanBar.setProgress(that.data.wxTimer);

        //计时结束
        if (tmpTime == "00:00") {
            console.log('计时结束');
            if (fn) {
                fn();
            }
            stop();
        }
        if (0 == (count - 1) % interval && intervalFn) {
            intervalFn();
        }

        if (that.data.startScanFlag === 0) {
            that.scanBar.startScan();
            that.setData({
                startScanFlag: 1,
            })
        }


    }, 1000);
    return intervarID;
}

function stop() {
    console.log(`# 定时执行结束 wxTimer_stop(${intervarID})`)
    clearInterval(intervarID);
}

module.exports = {
    wxTimer: wxTimer,
    wxTimerStop: stop
};